package network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class EchoServer {
    private DatagramSocket socket;
    public EchoServer(int port) throws SocketException {
        //端口号
        socket = new DatagramSocket(port);
    }
    public void  start() throws IOException{
        System.out.println("服务器启动");
        while(true){
            //1读取请求并解析
            //1)先创建一个空白的DatagramPacket对象
            DatagramPacket reqPacket=new DatagramPacket(new byte[4096],4096);
           //2)通过receive读取网卡的数据，如果网卡没有收到数据，会阻塞在这里
            socket.receive(reqPacket);
            //3）此时收到的reqPacket是二进制序列，我们修改成字符串
            //这个getData方法就是获取reqPacket中的二进制序列
            String request=new String(reqPacket.getData(),0,reqPacket.getLength());
            //2根据请求计算相应
            String response= process(request);
            //3把相应写到客户端
            //1）把相应构成的Datagrampacket对象
            DatagramPacket respPacket=new DatagramPacket(
                response.getBytes(),
                response.getBytes().length,
                reqPacket.getSocketAddress()//拿到客户端ip和端口
            );
            //2）通过socket把respPacket发送给客户端
            //原则上，谁发给我我就返回给谁
            socket.send(respPacket);
            //4打印日志
            System.out.printf("[%s:%d] req:%s,resp:%s\n",
            reqPacket.getAddress(),reqPacket.getPort(),request,response);
            //只拿ip                   
        }
    }

    //由于我们是回显服务器，所以响应和请求是一样的，这里就直接返回请求即可
   public String process(String request) {
        return request;
     
    }
    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(9000);
            server.start();
        
    }

}
